<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户统计</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <!-- 引入 ECharts -->
    <script src="../../js/echarts.js"></script>
    <style>
        .user-statistics-container {
            padding: 20px;
            background-color: #f5f7fa;
            min-height: 100vh;
        }
        .page-header {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ebeef5;
        }
        .statistics-cards {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 20px;
            gap: 20px;
        }
        .statistics-card {
            flex: 1;
            min-width: 250px;
            border-radius: 4px;
            background-color: #fff;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .card-title {
            font-size: 14px;
            color: #909399;
            margin-bottom: 12px;
        }
        .card-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
        }
        .card-trend {
            font-size: 12px;
            margin-top: 8px;
        }
        .trend-up {
            color: #f56c6c;
        }
        .trend-down {
            color: #67c23a;
        }
        .charts-container {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
        }
        .chart-card {
            flex: 1;
            min-width: 45%;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .chart-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #303133;
        }
        .chart-content {
            height: 300px;
        }
        .filter-container {
            margin-bottom: 20px;
            padding: 20px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 400px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="user-statistics-container">
        <div class="page-header">
            <h1>用户统计</h1>
            <p>系统用户数据概览与分析</p>
        </div>

        <!-- 筛选条件 -->
        <div class="filter-container">
            <el-form :inline="true" :model="filterForm" class="demo-form-inline">
                <el-form-item label="时间范围">
                    <el-date-picker
                            v-model="filterForm.dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select v-model="filterForm.deptId" placeholder="请选择部门" clearable>
                        <el-option
                                v-for="dept in deptOptions"
                                :key="dept.deptId"
                                :label="dept.deptName"
                                :value="dept.deptId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadData">查询</el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 统计卡片 -->
        <div class="statistics-cards">
            <div class="statistics-card">
                <div class="card-title">用户总数</div>
                <div class="card-value">{{ statistics.totalUsers || 0 }}</div>
                <div class="card-trend" :class="statistics.userGrowth >= 0 ? 'trend-up' : 'trend-down'">
                    <i :class="statistics.userGrowth >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(statistics.userGrowth || 0) }}% 较上月
                </div>
            </div>
            <div class="statistics-card">
                <div class="card-title">今日新增</div>
                <div class="card-value">{{ statistics.todayNewUsers || 0 }}</div>
            </div>
            <div class="statistics-card">
                <div class="card-title">活跃用户</div>
                <div class="card-value">{{ statistics.activeUsers || 0 }}</div>
                <div class="card-trend">最近7天</div>
            </div>
            <div class="statistics-card">
                <div class="card-title">管理员数量</div>
                <div class="card-value">{{ statistics.adminCount || 0 }}</div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div v-if="loading" class="loading-container">
            <el-icon class="is-loading" style="font-size: 32px;">
                <loading />
            </el-icon>
            <span style="margin-left: 10px;">数据加载中...</span>
        </div>

        <div v-else class="charts-container">
            <!-- 性别分布 -->
            <div class="chart-card">
                <div class="chart-title">用户性别分布</div>
                <div class="chart-content" ref="genderChart"></div>
            </div>

            <!-- 状态分布 -->
            <div class="chart-card">
                <div class="chart-title">用户状态分布</div>
                <div class="chart-content" ref="statusChart"></div>
            </div>

            <!-- 注册趋势 -->
            <div class="chart-card" style="min-width: 95%;">
                <div class="chart-title">用户注册趋势</div>
                <div class="chart-content" ref="trendChart" style="height: 350px;"></div>
            </div>

            <!-- 部门分布 -->
            <div class="chart-card">
                <div class="chart-title">用户部门分布</div>
                <div class="chart-content" ref="deptChart"></div>
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                filterForm: {
                    dateRange: [],
                    deptId: null
                },
                deptOptions: [],
                statistics: {},
                loading: false,
                genderChart: null,
                statusChart: null,
                trendChart: null,
                deptChart: null
            }
        },
        mounted() {
            this.loadDeptOptions();
            this.loadData();
           // this.initCharts();

            // 监听窗口变化，调整图表大小
            window.addEventListener('resize', this.resizeCharts);
        },
        beforeDestroy() {
            // 销毁时移除事件监听
            window.removeEventListener('resize', this.resizeCharts);

            // 销毁图表实例
            if (this.genderChart) this.genderChart.dispose();
            if (this.statusChart) this.statusChart.dispose();
            if (this.trendChart) this.trendChart.dispose();
            if (this.deptChart) this.deptChart.dispose();
        },
        methods: {
            // 初始化图表
            initCharts() {
                // 性别分布饼图
                this.genderChart = echarts.init(this.$refs.genderChart);
                this.genderChart.setOption({
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'horizontal',
                        bottom: 10,
                        data: ['男', '女', '未知']
                    },
                    series: [
                        {
                            name: '性别分布',
                            type: 'pie',
                            radius: ['50%', '70%'],
                            avoidLabelOverlap: false,
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '18',
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: []
                        }
                    ]
                });

                // 状态分布柱状图
                this.statusChart = echarts.init(this.$refs.statusChart);
                this.statusChart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: ['正常', '停用', '删除']
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '用户数',
                            type: 'bar',
                            data: [],
                            itemStyle: {
                                color: function(params) {
                                    const colorList = ['#91cc75', '#fac858', '#ee6666'];
                                    return colorList[params.dataIndex] || '#5470c6';
                                }
                            }
                        }
                    ]
                });

                // 注册趋势折线图
                this.trendChart = echarts.init(this.$refs.trendChart);
                this.trendChart.setOption({
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['注册用户数']
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: []
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '注册用户数',
                            type: 'line',
                            data: [],
                            smooth: true,
                            lineStyle: {
                                width: 3
                            },
                            areaStyle: {
                                opacity: 0.1
                            }
                        }
                    ]
                });

                // 部门分布环形图
                this.deptChart = echarts.init(this.$refs.deptChart);
                this.deptChart.setOption({
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        right: 10,
                        top: 'center',
                        data: []
                    },
                    series: [
                        {
                            name: '部门分布',
                            type: 'pie',
                            radius: ['40%', '70%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 10,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '16',
                                    fontWeight: 'bold'
                                }
                            },
                            labelLine: {
                                show: false
                            },
                            data: []
                        }
                    ]
                });
            },

            // 调整图表大小
            resizeCharts() {
                if (this.genderChart) this.genderChart.resize();
                if (this.statusChart) this.statusChart.resize();
                if (this.trendChart) this.trendChart.resize();
                if (this.deptChart) this.deptChart.resize();
            },

            // 加载部门选项
            loadDeptOptions() {
                // 获取部门列表
                axios.post('/vegetablemarketexpress/dept/list',{})
                    .then(response => {
                        if (response.data.code === 200) {
                            this.deptOptions = response.data.data;
                        }
                    })
                    .catch(error => {
                        console.error('获取部门列表失败:', error);
                        this.$message.error('获取部门列表失败');
                    });
            },

            // 加载数据
            loadData() {
                this.loading = true;

                // 构建请求参数
                const params = {};
                if (this.filterForm.dateRange && this.filterForm.dateRange.length === 2) {
                    params.startDate = this.filterForm.dateRange[0];
                    params.endDate = this.filterForm.dateRange[1];
                }
                if (this.filterForm.deptId) {
                    params.deptId = this.filterForm.deptId;
                }

                // 获取统计数据
                axios.get('/vegetablemarketexpress/user/statistics', { params })
                    .then(response => {
                        if (response.data.code === 200) {
                            this.statistics = response.data.data;
                            this.$nextTick(() => {
                                // 确保DOM已渲染完成
                                this.initCharts();
                                this.updateCharts();
                            });
                        } else {
                            this.$message.error(response.data.message || '获取数据失败');
                        }
                        this.loading = false;
                    })
                    .catch(error => {
                        console.error('获取统计数据失败:', error);
                        this.$message.error('获取统计数据失败');
                        this.loading = false;
                    });
            },

            // 更新图表数据
            updateCharts() {
                // 更新性别分布图表
                if (this.statistics.genderData) {
                    this.genderChart.setOption({
                        series: [{
                            data: this.statistics.genderData.map(item => ({
                                value: item.value,
                                name: item.name
                            }))
                        }]
                    });
                }

                // 更新状态分布图表
                if (this.statistics.statusData) {
                    const statusMap = {
                        '正常': 0,
                        '停用': 0,
                        '其他': 0
                    };

                    this.statistics.statusData.forEach(item => {
                        statusMap[item.name] = item.value;
                    });

                    this.statusChart.setOption({
                        series: [{
                            data: [statusMap['正常'], statusMap['停用'], statusMap['其他']]
                        }]
                    });
                }

                // 更新注册趋势图表
                if (this.statistics.trendData) {
                    const dates = [];
                    const values = [];

                    this.statistics.trendData.forEach(item => {
                        dates.push(item.date);
                        values.push(item.count);
                    });

                    this.trendChart.setOption({
                        xAxis: {
                            data: dates
                        },
                        series: [{
                            data: values
                        }]
                    });
                }

                // 更新部门分布图表
                if (this.statistics.deptData) {
                    this.deptChart.setOption({
                        legend: {
                            data: this.statistics.deptData.map(item => item.name)
                        },
                        series: [{
                            data: this.statistics.deptData.map(item => ({
                                value: item.value,
                                name: item.name
                            }))
                        }]
                    });
                }
            },

            // 重置筛选条件
            resetFilter() {
                this.filterForm = {
                    dateRange: [],
                    deptId: null
                };
                this.loadData();
            }
        }
    });
</script>
</body>
</html>